<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <th:block th:include="include :: header('用户管理')"/>
    <th:block th:include="include :: dtree_css"/>
</head>
<body class="x-admin-sm">
<div class="x-nav">
          <span class="layui-breadcrumb">
            <a href="">首页</a>
            <a>
              <cite>用户信息管理</cite></a>
          </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       onclick="location.reload()" title="刷新">
        <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
</div>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md2">
            <ul id="deptDTree" class="dtree" data-id="0"></ul>
        </div>
        <div class="layui-col-md10">
            <div class="layui-card">
                <div class="layui-card-body ">
                    <form class="layui-form layui-col-space5">
                        <div class="layui-inline layui-show-xs-block">
                            <input class="layui-input" autocomplete="off" placeholder="登录账号" name="loginName"
                                   id="loginName">
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <input class="layui-input" autocomplete="off" placeholder="邮箱" name="email" id="email">
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <input type="text" name="phonenumber" id="phonenumber" placeholder="手机号" autocomplete="off"
                                   class="layui-input">
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <button class="layui-btn" lay-submit="" lay-filter="search"><i
                                    class="layui-icon">&#xe615;</i></button>
                        </div>
                    </form>
                </div>
                <div class="layui-card-body">
                    <table id="userlist" lay-filter="tb_user_filter"></table>
                </div>
            </div>
        </div>
    </div>
</div>

</body>

<!--表格操作-->
<script type="text/html" id="toolbarUser">
    <div style="font-size: 12px">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="default">重置</a>
    </div>
</script>

<!--表格上方 操作功能键-->
<script type="text/html" id="toolUser">
    <div class="layui-card-header">
        <button class="layui-btn layui-btn-danger" lay-event="delAll"><i class="layui-icon"></i>批量删除
        </button>
        <button id="btnAdd" class="layui-btn" lay-event="add"><i class="layui-icon"></i>添加</button>
    </div>
</script>

<!--状态-->
<script type="text/html" id="switchUserStatus">
    <input style="font-size: 12px" type="checkbox" name="status" value="{{d.status}}" lay-skin="switch" lay-text="启用|暂停"
           lay-filter="userStatusFilter" {{ d.status== 0 ? 'checked' : '' }}>
</script>


<th:block th:include="include :: dtree_js"/>
<script th:inline="javascript"> var ctx = [[@{/}]] </script>
<script>
    layui.use(['laydate', 'form', 'table', 'dtree'], function () {
        var laydate = layui.laydate;
        var form = layui.form;
        var table = layui.table;
        var dtree = layui.dtree;


        //执行一个laydate实例
        laydate.render({
            elem: '#start' //指定元素
        });

        //执行一个laydate实例
        laydate.render({
            elem: '#end' //指定元素
        });


        var deptDtree = dtree.render({
            elem: '#deptDTree',
            url: ctx + 'system/dept/detpDtree',
            method: 'POST',
            dataStyle: "layuiStyle",  //使用layui风格的数据格式
            dataFormat: "list",  //配置data的风格为list
            icon: ["0", "5"],
            response: {
                statusName: "code", //返回标识（必填）
                statusCode: 0, //返回码（必填）
                message: "msg", //返回信息（必填）
                rootName: "data", //根节点名称（必填）
                treeId: "id", //节点ID（必填）
                parentId: "parentId", //父节点ID（必填）
                title: "title", //节点名称（必填）
            },
            success: function (data, ul, first) {

                // console.log(data);
            }

        });

        dtree.on('node("deptDTree")', function (obj) {
            var _id = obj.param.nodeId;
            var _parentId = obj.param.parentId;
            table.reload('userlist', {
                where: {
                    deptId: _id,
                },
            });


        });

        var userTable = table.render({
            elem: '#userlist',
            url: ctx + 'system/user/list',
            method: 'post',
            skin: 'line',
            toolbar: '#toolUser',
            even: true,
            page: {
                groups: 3,
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip']
            },
            // size: 'sm', //小尺寸的表格
            cols: [
                [
                    {type: 'checkbox', fixed: 'left'}
                    , {field: 'userId', title: '账号ID', width: 80}
                    , {field: 'loginName', title: '登录账号', width: 80}
                    , {field: 'userName', title: '用户昵称', width: 120}
                    , {field: 'email', title: '用户邮箱', width: 180}
                    , {field: 'phonenumber', title: '手机号码', width: 140}
                    , {field: 'status', title: '帐号状态', templet: '#switchUserStatus', width: 110}
                    , {field: 'loginIp', title: '最后登陆IP', sort: true, width: 120}
                    , {
                    field: 'loginDate',
                    width: 200,
                    title: '最后登陆时间',
                    sort: true,
                    templet: '<div>{{ layui.util.toDateString(d.loginDate, "yyyy-MM-dd HH:mm:ss") }}</div>'
                }
                    , {
                    field: 'updateTime',
                    width: 200,
                    title: '更新时间',
                    sort: true,
                    templet: '<div>{{ layui.util.toDateString(d.updateTime, "yyyy-MM-dd HH:mm:ss") }}</div>'
                }
                    , {fixed: 'right', width: 200, align: 'center', toolbar: '#toolbarUser'}
                ]
            ],
            done: function (res, curr, count) {
                //设置表格样式

                $(".layui-table").css({
                    "border": "1px solid #e2e2e2",
                    "border-top": "none",
                    "width": "100%"
                });
                $("thead").css("border-top", "1px solid #e2e2e2");
            },
            parseData: function (res) {
                return {
                    "code": res.code,
                    "count": res.total,
                    "data": res.rows,
                }

            },
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            }

        });

        table.on('tool(tb_user_filter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                editUser(data)
            } else if (obj.event === 'del') {
                delUser(data);
            } else if (obj.event === 'default') {
                defaultUser(data);
            }
        });

        table.on('toolbar(tb_user_filter)', function (obj) {

            var data = obj.data;

            switch (obj.event) {
                case 'delAll':
                    delUserBatch(data);
                    break;
                case 'add':
                    xadmin.open('添加用户', '/system/user/adduser', 600, 500);
                    break;
                case 'reload':
                    reloadTable();
                    break;
            }

        })

        form.on('submit(search)', function (data) {
            userTable.reload({
                where: {
                    loginName: $('#loginName').val(),
                    email: $('#email').val(),
                    phonenumber: $('#phonenumber').val(),
                }
            });
            return false;
        });

        function editUser(_data) {
            // layer.msg('ID：' + data.loginName + ' 的查看操作');
            layer.open({
                type: 2,
                area: ['600px', '540px'],
                fix: false, //不固定
                maxmin: true,
                shadeClose: true,
                shade: 0.4,
                title: '编辑用户',
                content: ctx + "system/user/edituser?loginName=" + _data.loginName,
            });
        }


        /**
         * 删除用户信息按钮事件
         * @param data
         */
        function delUser(data) {
            layer.confirm('真的删除行么', function (index) {
                $.ajax({
                    url: ctx + 'system/user/delUser?loginName=' + data.loginName,
                    type: 'POST',
                    success: function (res) {

                        if (res.code == 0) {
                            layer.msg("删除成功", {icon: 1})
                        } else {
                            layer.msg("删除失败", {icon: 5})
                        }
                        userTable.reload();
                    }

                });
                layer.close(index);
            });
        }

        /**
         * 重置密码
         * @param data
         */
        function defaultUser(data) {
            // layer.msg("重置用户密码功能调用"+JSON.stringify(data));
            var _userId = data.userId;
            layer.confirm('确定要重置用户密码么？', function (index) {
                $.ajax({
                    url: ctx + 'system/user/reset',
                    type: 'POST',
                    data: {uId: _userId},
                    success: function (res) {

                        if (res.code == 0) {
                            layer.msg(res.msg, {icon: 1})
                        } else {
                            layer.msg(res.msg, {icon: 5})
                        }
                        userTable.reload();
                    }

                });
                layer.close(index);
            });


        }


        // // 状态修改 事件监听
        // form.on('switch(userStatusFilter)', function (obj) {
        //     layer.tips(this.value + ' ' + this.name + '：' + obj.elem.checked, obj.othis);
        // });


        function delUserBatch() { //获取选中数据
            var checkStatus = table.checkStatus('userlist');
            if (checkStatus.data.length < 1) {
                layer.msg("请选择要删除的用户行", {icon: 5});
                return;
            }

            layer.confirm('确定要删除选中的数据吗？', function (index) {
                var data = checkStatus.data.map(item => {
                    return item.userId
                }).join();
                // ajax 请求服务端 做批量删除操作

                $.ajax({
                    url: ctx + 'system/user/remove',
                    type: 'POST',
                    data: {ids: data},
                    success: function (res) {

                        if (res.code == 0) {
                            layer.msg("批量操作成功", {icon: 1})
                        } else {

                            layer.msg("批量操作失败", {icon: 5})
                        }
                        userTable.reload();
                    }

                });
                layer.close(index);

            });

            // layer.msg(JSON.stringify(data));
        }


        var $ = layui.$, active = {};


        $('#userDelBatch').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });


        function reloadTable() {

            table.reload('userlist');
        }


    });


</script>
</html>